package com.boshao.classschedule.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.text.format.Time;

import com.boshao.classschedule.model.DateInfo;

/**
 * 时间工具类
 * @author boshao
 *
 */
public class TimeUtils {
	/**
	 *获取今天的年份
	 * @return
	 */
	public static int getCurrentYear() {
		Time t = new Time();
		t.setToNow();
		return t.year;
	}
	/**
	 * 获取今天的月份
	 * @return
	 */
	public static int getCurrentMonth() {
		Time t = new Time();
		t.setToNow();
		return t.month + 1;
	}
	/**
	 * 获取今天的天数
	 * @return
	 */
	public static int getCurrentDay() {
		Time t = new Time();
		t.setToNow();
		return t.monthDay;
	}
	
	/**
	 * 根据viewpager的位置获取年份和月份
	 * @param position
	 * @param originYear
	 * @param originMonth
	 * @param type
	 * @return
	 */
	public static int getTimeByPosition(int position, int originYear, int originMonth, String type) {
    	int year = originYear, month = originMonth;
    	if (position > 500) {
    		for (int i = 500; i < position; i++) {
    			month++;
    			if (month == 13) {
    				month = 1;
    				year++;
    			}
    		}
    	} else if (position < 500) {
    		for (int i = 500; i > position; i--) {
    			month--;
    			if (month == 0) {
    				month = 12;
    				year--;
    			}
    		}
    	}
    	if (type.equals("year")) {
    		return year;
    	}
    	return month;
	}
	
	/**
	 * 获取该date的星期   date的格式 2015-01-01
	 * @param date
	 * @return 0  表示  星期日  1 表示星期一
	 */
	public static int getWeekDay(String date) {  
        Calendar calendar = getCalendarOfDate(date);  
        int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);  
        if (dayOfWeek == 1) {
            dayOfWeek = 0;  
        }
        else {
            dayOfWeek -= 1; 
        }
        return dayOfWeek;  
    }
	
	/**
	 * 获取给予date的calendar对象
	 * date格式: yyyy-MM-dd
	 * @param date
	 * @return
	 */
	public static Calendar getCalendarOfDate(String date) {
		Calendar calendar = Calendar.getInstance();  
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");  
        try {  
            calendar.setTime(sdf.parse(date));  
        } catch (ParseException e) {  
            e.printStackTrace();  
        }
		return calendar;
	}  
	
	/**
	 * 判断是否闰年
	 * @param year
	 * @return true 是闰年
	 */
	public static boolean isLeapYear(int year) {
		if (year % 400 == 0 || year % 100 != 0 && year % 4 == 0) {
			return true;
		}
		return false;
	}
	
	/**
	 * 获取该月的天数
	 * @param year
	 * @param month
	 * @return
	 */
	public static int getDaysOfMonth(int year, int month) {
		switch (month) {
		case 1:
		case 3:
		case 5:
		case 7:
		case 8:
		case 10:
		case 12:
			return 31;
		case 4:
		case 6:
		case 9:
		case 11:
			return 30;
		default:
			if (isLeapYear(year)) {
				return 29;
			}
			return 28;
		}
	}
	
	/**
	 * 获取该date的所处的那个星期的一周日期和星期
	 * @param date
	 * @return map<String,Integer>
	 * 	string: 格式2015-05-01
	 *  integer: 0 - 周日    1 - 周一
	 */
	public static Map<Integer,String> getCurrentWeekDays(String date){
		Map<Integer,String> map = new HashMap<Integer,String>();
		Calendar currentCalendar = getCalendarOfDate(date);
		int currentdayofweek = currentCalendar.get(Calendar.DAY_OF_WEEK);
		int flag = currentdayofweek;
		Calendar flagCalendar = currentCalendar;
		map.put(currentdayofweek-1,date);
		for(int i = 0;i < 6;i++){
			if(currentdayofweek + 1 <= 7){
				currentdayofweek++;
				Calendar calendar = Calendar.getInstance();
				calendar.setTimeInMillis(currentCalendar.getTimeInMillis()+getOneDayMilliseconds());
				map.put(calendar.get(Calendar.DAY_OF_WEEK) - 1,getFormatDate(calendar.get(Calendar.YEAR),calendar.get(Calendar.MONTH)+1
						,calendar.get(Calendar.DAY_OF_MONTH)));
				currentCalendar = calendar;
			}
		}
		for(int i = 0;i < 6;i++){
			if(flag - 1 > 0){
				flag--;
				Calendar calendar = Calendar.getInstance();
				calendar.setTimeInMillis(flagCalendar.getTimeInMillis() - getOneDayMilliseconds());
				map.put(calendar.get(Calendar.DAY_OF_WEEK) -1,getFormatDate(calendar.get(Calendar.YEAR),calendar.get(Calendar.MONTH)+1
						,calendar.get(Calendar.DAY_OF_MONTH)));
				flagCalendar = calendar;
			}
		}
		return initMapDaysOfWeek(map);
	}
	
	private static Map<Integer,String> initMapDaysOfWeek(Map<Integer,String> resultMap){
		Map<Integer,String> map = new HashMap<>();
		for(Map.Entry<Integer, String> entry:resultMap.entrySet()){
			if(entry.getKey() == 0){
				Calendar calendar = getCalendarOfDate(entry.getValue());
				Calendar calendarAfter7day = Calendar.getInstance();
				calendarAfter7day.setTimeInMillis(calendar.getTimeInMillis()+7 * getOneDayMilliseconds());
				map.put(6,getFormatDate(calendarAfter7day.get(Calendar.YEAR),calendarAfter7day.get(Calendar.MONTH)+1
						,calendarAfter7day.get(Calendar.DAY_OF_MONTH)));
			}else{
				map.put(entry.getKey() - 1,entry.getValue());
			}
		}
		return map;
	}
	
	private static final String  DEFAULT = "2015-03-09";
	/**
	 * 获取今天是开学的周数  (默认开学日期为：2015-03-09)
	 * @param date
	 * @return
	 */
	public static int getNumberOfWeeks(String date){
		Calendar calendar = getCalendarOfDate(date);
		int dayOfYear = calendar.get(Calendar.DAY_OF_YEAR);
		Calendar defaultCalendar = getCalendarOfDate(DEFAULT);
		int defDayOfYear = defaultCalendar.get(Calendar.DAY_OF_YEAR);
		return (dayOfYear - defDayOfYear) / 7 + 1; 
	}
	
	/**
	 * 获取一天的毫秒数
	 * @return
	 */
	public static int getOneDayMilliseconds(){
		return 86400000;
	}
	
	/**
	 * 格式化Date的年、月
	 * @param year
	 * @param month
	 * @return	string 格式：2015-02-01
	 */
	public static String getFormatDate(int year, int month) {
    	String formatYear = year + "";
    	String formatMonth = "";
    	if (month < 10) {
    		formatMonth = "0" + month;
    	} else {
    		formatMonth = month + "";
    	}
    	return formatYear + "-" + formatMonth + "-01";
	}
	
	
	/**
	 * 格式化Date的年、月、日
	 * @param year
	 * @param month
	 * @param day
	 * @return	string 格式：2015-02-03
	 */
	public static String getFormatDate(int year, int month, int day) {
    	String formatYear = year + "";
    	String formatMonth = "";
    	String formatDay = "";
    	if (month < 10) {
    		formatMonth = "0" + month;
    	} else {
    		formatMonth = month + "";
    	}
    	if (day < 10) {
    		formatDay = "0" + day;
    	} else {
    		formatDay = day + "";
    	}
    	return formatYear + "-" + formatMonth + "-" + formatDay;
	}
	
	public static List<DateInfo> initCalendar(String formatDate, int month) throws Exception {
		int dates = 1;
		int year = Integer.parseInt(formatDate.substring(0, 4));
		int [] allDates = new int[42];
		for (int i = 0; i < allDates.length; i++) {
			allDates[i] = -1;
		}
		int firstDayOfMonth = TimeUtils.getWeekDay(formatDate);
		int totalDays = TimeUtils.getDaysOfMonth(year, month);
		for (int i = firstDayOfMonth; i < totalDays + firstDayOfMonth; i++) {
    		allDates[i] = dates;
    		dates++;
    	}
		
		List<DateInfo> list = new ArrayList<DateInfo>();
		DateInfo dateInfo;
		for (int i = 0; i < allDates.length; i++) {
    		dateInfo = new DateInfo();
    		dateInfo.setDate(allDates[i]);
    		if (allDates[i] == -1) {
    			dateInfo.setNongliDate("");
    			dateInfo.setThisMonth(false);
    			dateInfo.setWeekend(false);
    		}
    		else {
    			String date = TimeUtils.getFormatDate(year, month, allDates[i]);
    			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    			long time = sdf.parse(date).getTime();
    			Lunar lunar = new Lunar(time);
    			if (lunar.isSFestival()) {//是不是公历节日
					dateInfo.setNongliDate(lunar.getSFestivalName());
					dateInfo.setHoliday(true);
				} else {
					if (lunar.isLFestival() && lunar.getLunarMonthString().substring(0, 1).equals("闰") == false) {
						dateInfo.setNongliDate(lunar.getLFestivalName());
						dateInfo.setHoliday(true);
					} else {
						if (lunar.getLunarDayString().equals("初一")) {
							dateInfo.setNongliDate(lunar.getLunarMonthString() + "月");
						} else {
							dateInfo.setNongliDate(lunar.getLunarDayString());
						}
						dateInfo.setHoliday(false);
					}
				}
    			dateInfo.setThisMonth(true);
    			int t = getWeekDay(getFormatDate(year, month, allDates[i]));
    			if (t == 0 || t == 6) {
    				dateInfo.setWeekend(true);
    			}
    			else {
    				dateInfo.setWeekend(false);
    			}
    		}
    		list.add(dateInfo);
    	}
    	
    	int front = DataUtils.getFirstIndexOf(list);
    	int back = DataUtils.getLastIndexOf(list);
    	int lastMonthDays = getDaysOfMonth(year, month - 1);
    	int nextMonthDays = 1;
    	for (int i = front - 1; i >= 0; i--) {
    		list.get(i).setDate(lastMonthDays);
    		lastMonthDays--;
    	}
    	for (int i = back + 1; i < list.size(); i++) {
    		list.get(i).setDate(nextMonthDays);
    		nextMonthDays++;
    	}
    	return list;
	}
}
